

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/base/Refresher.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';

import 'LessonItem.dart';
import 'model/LessonModel.dart';

class LessonListPageWithAppBar extends StatefulWidget {
  
  final int? categoryId;
  final String? title;
  final int? type; //1.普通课程 2.大师课程 #默认全部
  final int? recommendStatus; //是否热门推荐 0.否 1.是
  final int? isNewSale; //是否最新上架 0.否 1.是

  const LessonListPageWithAppBar(this.categoryId, this.title, {
    Key? key,
    this.type,
    this.recommendStatus,
    this.isNewSale
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LessonListPageWithAppBarState();
  }
}

class _LessonListPageWithAppBarState extends BaseState<LessonListPageWithAppBar> {

  int page = 1;
  
  @override
  void initState() {
    super.initState();
    refresher = Refresher<Lesson>(this);
    load(false);
  }

  load(bool doNotShowProgressBar) {
    var data = {
      'list_rows': 10,
      'page': page,
      'lesson_type': widget.type, //课程类型 1.普通课程 2.大师课程 #默认全部
      'category_id': widget.categoryId,
      'recommend_status': widget.recommendStatus,
      'is_new_sale': widget.isNewSale
    };
    sendReq(Api.lessonList(), LessonListResp(), data: data, doNotShowProgressBar: doNotShowProgressBar);

  }

  @override
  void onRefresh() {
    refresher?.mode = Mode.refresh;
    page = 1;
    load(true);
  }

  @override
  void onLoadMore() {
    refresher?.mode = Mode.loadMore;
    load(true);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is LessonListResp) {
      // lessons = t.data?.data;
      refresher?.load(t.data?.data);
      page++;
      setState(() => null);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: CAppBar(title: widget.title ?? '', overlayStyle: SystemUiOverlayStyle.dark),
        body: refresher?.build(buildChild())
    );

  }

  Widget? buildChild() {
    print('buildChild');
    Widget? child = buildEmptyPage();
    if (child != null) {
      print('empty buildChild');
      return child;
    }
    return
      ListView.separated(
          itemBuilder: (_, index) {
            double top = 0, bottom = 0;
            if (index == 0) top = 13;
            if (index == (refresher?.data?.length ?? 0) - 1) bottom = 13;
            return Padding(padding: EdgeInsets.only(left: 13, right: 13, top: top, bottom: bottom),
                child: LessonItem(refresher?.data?[index]));
          },
          separatorBuilder: (_, index) => H(15),
          itemCount: (refresher?.data?.length ?? 0)
      );
  }
}